<template>
  <div style="padding: 10px">
    <top-tip :tipcontent="tipcontent" />
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card shadow="never">
          <el-descriptions title="导入Excel文件" border />
          <el-form>
            <el-form
              ref="formRef"
              label-width="140px"
              :model="form"
              :rules="rules"
            >
              <el-form-item label="所属组织" prop="CompanyID">
                <el-cascader
                  v-model="form.CompanyID"
                  :options="CompanyOptions"
                  :props="companyProps"
                  clearable
                  @change="getDeptment"
                />
              </el-form-item>
              <el-form-item label="所属部门" prop="DepartmentID">
                <el-cascader
                  v-model="form.DepartmentID"
                  :options="DeptmentOptions"
                  :props="deptmentProps"
                  clearable
                  @change="getStaffPost"
                />
              </el-form-item>
              <!-- <el-form-item label="职位" prop="StaffPostID">
                <el-cascader
                  v-model="form.StaffPostID"
                  :options="StaffPostRoleOptions"
                  :props="StaffPostProps"
                  clearable
                  @change="getStaffPostProps"
                />
              </el-form-item> -->
              <el-form-item label="选择导入目标员工" prop="StaffID">
                <el-cascader
                  v-model="form.StaffID"
                  :options="staffList"
                  :props="StaffProps"
                  clearable
                  @change="selectEmployees"
                />
              </el-form-item>
              <div
                style="
                  padding: 10px;
                  border: 1px solid #ffcccc;
                  margin-bottom: 10px;
                "
              >
                请按照
                <a
                  href="https://api.sanjianke.com/public/批量客户导入标准.xlsx"
                >
                  导入标准
                </a>
                整理好 Excel 文件，
                <br />
                确认无误后，上传文件，确定导入即可！
              </div>
              <el-form-item label-width="0">
                <div style="width: 100%">
                  <!-- multiple -->
                  <el-upload
                    ref="uploadFile"
                    v-model:file-list="fileList"
                    drag
                    show-file-list
                    :before-upload="beforeAvatarUpload"
                    action="https://api.sanjianke.com/common/Upload/upload?file=customer&type=attachment"
                    :on-success="changeFileList"
                    :on-remove="removeFile"
                    :limit="1"
                    :on-exceed="handleExceed"
                    style="width: 100%"
                  >
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">
                      拖拽附件文件到这里
                      <em>或点击上传</em>
                    </div>
                  </el-upload>
                </div>
              </el-form-item>
            </el-form>
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="save">确定导入</el-button>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card shadow="never">
          <el-descriptions title="数据预览" border />
          <el-table
            ref="orgidslistRef"
            v-loading="listLoading"
            :data="list"
            @selection-change="setSelectRows"
          >
            <el-table-column
              align="center"
              show-overflow-tooltip
              type="selection"
            />
            <el-table-column
              align="center"
              label="客户全称"
              prop="CustomerAllName"
              show-overflow-tooltip
            />
            <el-table-column
              align="center"
              label="地址"
              prop="Telphone"
              show-overflow-tooltip
            />
            <el-table-column
              align="center"
              label="业务联系人"
              prop="BusinessPerson"
              show-overflow-tooltip
            />
            <el-table-column
              align="center"
              label="业务联系人电话"
              prop="BusinessPersonMobile"
              show-overflow-tooltip
            />
            <el-table-column
              align="center"
              label="主营产品"
              prop="SalesProducts"
              show-overflow-tooltip
            />
            <el-table-column
              align="center"
              label="主要销售区域"
              prop="SalesArea"
              show-overflow-tooltip
            />
            <el-table-column
              align="center"
              label="主要客户群体"
              prop="CustomerGroup"
              show-overflow-tooltip
            />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import {
    getStaffPostRoleSelect,
    getBusinessClassSelect,
    getCompanySelect,
    getDeptmentSelect,
    ImportCustomer,
    GetStaffSelect,
  } from '@/api/common'
  import TopTip from '@/components/TopTip'
  import { ElMessage } from 'element-plus'

  export default defineComponent({
    name: 'CreateCustomer',
    components: { TopTip },
    setup() {
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        formRef: null,
        uploadFile: null,
        orgidslistRef: null,
        companyProps: {
          checkStrictly: true,
        },
        rules: {
          CompanyID: [
            { required: true, trigger: 'blur', message: '请选择所属组织' },
          ],
          DepartmentID: [
            { required: true, trigger: 'blur', message: '请选择所属部门' },
          ],
        },
        deptmentProps: {
          checkStrictly: true,
        },
        StaffPostProps: {},
        tipcontent: {
          title: '关于批量导入客户资源',
          memo: '本页用于为合同业务单开具发票；默认显示新提单未确认开发票的合同业务单；',
        },
        list: [],
        staffList: [],
        selectRows: '',
        CompanyOptions: [],
        DeptmentOptions: [],
        BusinessClassOptions: [],
        StaffPostRoleOptions: [],
        custList: [],
        StaffProps: {
          label: 'StaffName',
          value: 'StaffID',
          multiple: false,
          checkStrictly: true,
        },
        StaffOptions: [],
        form: {
          currentCompany: 0,
          targetDeptment: [],
        },
      })

      // 删除文件后
      const removeFile = (e) => {
        console.log(e, '删除文件')
      }

      // 上传成功后
      const changeFileList = (e, list) => {
        // state.list = state.list.concat(e.filesContent)
        console.log(list, '123123')
        state.list = e.filesContent
        state.list.forEach((item) => {
          nextTick(() => {
            state.orgidslistRef.toggleRowSelection(item, true)
          })
        })
      }

      const getOptions = async () => {
        state.listLoading = true
        const {
          data: { BusinessClassOptions },
        } = await getBusinessClassSelect()
        const {
          data: { CompanyOptions },
        } = await getCompanySelect()
        const {
          data: { StaffPostRoleOptions },
        } = await getStaffPostRoleSelect()
        state.BusinessClassOptions = BusinessClassOptions
        state.CompanyOptions = CompanyOptions
        state.StaffPostRoleOptions = StaffPostRoleOptions
        state.listLoading = false
      }

      // 选择组织后
      const getDeptment = async () => {
        console.log('form.Company', state.form.CompanyID)
        if (state.form.CompanyID) {
          const getParams = {
            Company: [state.form.CompanyID],
          }
          const {
            data: { DeptmentOptions },
          } = await getDeptmentSelect(getParams)
          state.DeptmentOptions = DeptmentOptions
        } else {
          state.form.DepartmentID = []
          state.DeptmentOptions = []
          state.form.StaffID = []
          state.staffList = []
        }
      }
      // 选择部门后
      const getStaffPost = async () => {
        console.log(state.form.DepartmentID, 'state.form.TaskDeptment')
        if (state.form.DepartmentID) {
          const getParams = {
            Deptment: state.form.DepartmentID,
            StaffPostID: [],
          }
          console.log(getParams, 'getParamsgetParamsgetParams')
          const {
            data: { StaffPostOptions },
          } = await GetStaffSelect(getParams)
          state.staffList = StaffPostOptions
        } else {
          state.form.StaffID = []
          state.staffList = []
        }
      }
      const beforeAvatarUpload = (rawFile) => {
        const extension = rawFile.name.substring(
          rawFile.name.lastIndexOf('.') + 1
        )
        if (extension !== 'xls' && extension !== 'xlsx') {
          ElMessage.error('只能上传Excel的文件')
          return false
        }
        return true
      }
      // 覆盖
      const handleExceed = (rawFile) => {
        state.uploadFile.clearFiles()
        state.uploadFile.handleStart(rawFile[0])
        state.uploadFile.submit()
      }
      // 选择员工后
      const selectEmployees = async () => {
        const getParams = {
          Company: state.form.CompanyID,
          Deptment: state.form.DepartmentID,
          StaffPostID: state.form.StaffPostID,
        }
        console.log(getParams, '123123')
      }

      const setSelectRows = (val) => {
        state.selectRows = val
        state.custList = val
      }
      const save = async () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            if (state.custList.length == 0) {
              ElMessage({
                message: '上传数据不能为空',
                type: 'warning',
              })
              return
            }
            let staffID = 0
            if (state.form.StaffID) {
              staffID = state.form.StaffID[0]
            } else {
              staffID = 0
            }
            const dataMsg = {
              CompanyID: state.form.CompanyID[state.form.CompanyID.length - 1],
              DepartmentID:
                state.form.DepartmentID[state.form.DepartmentID.length - 1],
              StaffID: staffID,
              CustomerData: state.custList,
            }
            const { data } = await ImportCustomer(dataMsg)
            console.log('确认导入')
            if (data == 200) {
              $baseMessage('导入成功', 'success', 'vab-hey-message-success')
              state.uploadFile.clearFiles()
              state.list = []
              state.custList = []
            }
          }
        })
      }

      onMounted(() => {
        const currentCompanys = JSON.parse(localStorage.getItem('currCompany'))
        state.form.currentCompany = currentCompanys['CompanyID']
        getOptions()
      })

      return {
        ...toRefs(state),
        getOptions,
        getDeptment,
        getStaffPost,
        selectEmployees,
        beforeAvatarUpload,
        handleExceed,
        save,
        setSelectRows,
        changeFileList,
        removeFile,
      }
    },
  })
</script>

<style lang="scss" scoped></style>
